package com.yeban.javase.day06.test04_localtime;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/14
 *
 * 8.新闻类：标题，内容，时间   三个属性。 有10条新闻，按照时间的降序排列。
 */
public class test08 {

    public static void main(String[] args) {
        News[] news = new News[10];

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int i = 0; i < news.length; i++) {
            int year = (int)(Math.random()*11 + 2015);      // 2015-2025年随机
            int month = (int)(Math.random()*12 + 1);        // 1-12月随机
            int day = (int)(Math.random()*28 + 1);          // 1-28日随机

            String monthStr = (month < 10) ? "0" + month : String.valueOf(month);
            String dayStr = (day < 10) ? "0" + day : String.valueOf(day);
            String timeStr = year + "-" + monthStr + "-" + dayStr;

            // 关键：为每个数组元素创建 News 实例（避免null）
            news[i] = new News();
            news[i].setTitle("标题" + i);
            news[i].setContent("内容" + i);
            news[i].setTime(timeStr);
        }

        Arrays.sort(news, new Comparator<News>() {
            @Override
            public int compare(News o1, News o2) {
                // 自定义比较逻辑
                LocalDate localDate1 = LocalDate.parse(o1.getTime(), formatter);
                LocalDate localDate2 = LocalDate.parse(o2.getTime(), formatter);
                // 降序逻辑：date2.compareTo(date1)
                return localDate2.compareTo(localDate1);
            }
        });

        for(News n : news) {
            System.out.println(n);
        }
    }
}

class News {
    private String title;
    private String content;
    private String time;

    public News() {
    }

    public News(String title, String content, String time) {
        this.title = title;
        this.content = content;
        this.time = time;
    }

    /**
     * 获取
     * @return title
     */
    public String getTitle() {
        return title;
    }

    /**
     * 设置
     * @param title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * 获取
     * @return content
     */
    public String getContent() {
        return content;
    }

    /**
     * 设置
     * @param content
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * 获取
     * @return time
     */
    public String getTime() {
        return time;
    }

    /**
     * 设置
     * @param time
     */
    public void setTime(String time) {
        this.time = time;
    }

    public String toString() {
        return "News{title = " + title + ", content = " + content + ", time = " + time + "}";
    }
}
